#include "MaterialLib.hpp"

#include <fstream>
#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>

#include "Exception.hpp"

using namespace std;
using namespace boost;

void MaterialLib::Load(string Filename, string Path)
{
	
	ifstream File( (Path+Filename).c_str() );
	string Line;
	if(!File.is_open())
	{
		THROW(Exception() << ex_message("MaterialLib not found") << ex_file(Path+Filename));
	}
	
	string curName;
	while(!File.eof())
	{
		getline(File, Line);
		trim_if(Line, is_any_of(" \n\r"));//remove whitespaces	
		if(Line.empty())
			continue;
	
		vector<string> SplitedLine;
		boost::split(SplitedLine, Line, is_any_of(" "));

		if(SplitedLine.size()<2)//we need at least 2 words
			continue;

		if("newmtl"==SplitedLine[0])
		{
			curName=SplitedLine[1];
			m_Materials[curName]=Material();
		}
		else if("map_Kd"==SplitedLine[0])
		{
			//todo: well we should store references in the map...
			Material mat=m_Materials[curName];
			mat.LoadTexture(Path+boost::replace_all_copy(SplitedLine[1], "\\", "/"));
			m_Materials[curName]=mat;
		}
		//Todo: load other material properties
	}
}

Material MaterialLib::GetMaterial(std::string Name)
{
	if(m_Materials.find(Name)==m_Materials.end())
	{
		THROW(Exception() << ex_message("Material not found") << ex_detail(Name));
	}

	return m_Materials[Name];
}
